﻿namespace kad2SimSoft {
    using kad2SimSoft.Classes;
    using kad2SimSoft.Resources.Lokalisierung;
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Input;
    using System.Windows.Media;

    public partial class PurchasingPartsControl : UserControl {

        private List<PurchasedPart> _purchasedParts = new List<PurchasedPart>();
        private List<Forecast> _forecasts = new List<Forecast>();
        private List<Order> _orders = new List<Order>();

        private Dictionary<int, TextBox> dictTbOrders = new Dictionary<int, TextBox>();
        private Dictionary<int, TextBox> dictTbOderCosts = new Dictionary<int, TextBox>();
        private Dictionary<int, TextBox> dictTbPartIDs = new Dictionary<int, TextBox>();
        private Dictionary<int, CheckBox> dictChbOrderTypes = new Dictionary<int, CheckBox>();
        private Dictionary<int, TextBox> dictTbOrderCostInSum = new Dictionary<int, TextBox>();

        private int _actualPeriod;
        private bool isLoaded = false;
        bool isAlternateRow = true;

        public List<PurchasedPart> PurchasedParts {
            get { return _purchasedParts; }
        }

        //############## CONSTRUCTOR #####################
        public PurchasingPartsControl (List<PurchasedPart> purchasedParts, List<Forecast> forecasts, int actualPeriod) {
            InitializeComponent();

            if (purchasedParts.Count == 0 | forecasts.Count == 0) {
                throw new NoNullAllowedException();
            }
            else {
                this._purchasedParts = purchasedParts;
                this._forecasts = forecasts;
                this._actualPeriod = actualPeriod;
            }

        }
        //############## INTERNAL CUSTOM CONTROLS ########
        public static MainWindow FindPageControl (DependencyObject child) {

            DependencyObject parent = VisualTreeHelper.GetParent(child);

            if (parent == null) return null;

            MainWindow page = parent as MainWindow;
            if (page != null) {
                return page;
            }
            else {
                return FindPageControl(parent);
            }


        }
        //############## START ADDING CONTROLS #############
        private void initTextBoxesForecasts () {

            foreach (Order order in _orders) {
                if (order.Product.Id == 1) {
                    if (order.Amount > 0) {
                        P1n.Text = order.Amount.ToString();
                    }
                    else {
                        P1n.Text = "0";
                    }
                }
                else if (order.Product.Id == 2) {
                    if (order.Amount > 0) {
                        P2n.Text = order.Amount.ToString();
                    }
                    else {
                        P2n.Text = "0";
                    }
                }
                else if (order.Product.Id == 3) {
                    if (order.Amount > 0) {
                        P3n.Text = order.Amount.ToString();
                    }
                    else {
                        P3n.Text = "0";
                    }
                }
            }

            P1n1.Text = _forecasts[3].Count.ToString();
            P1n2.Text = _forecasts[6].Count.ToString();
            P1n3.Text = _forecasts[9].Count.ToString();

            P2n1.Text = _forecasts[4].Count.ToString();
            P2n2.Text = _forecasts[7].Count.ToString();
            P2n3.Text = _forecasts[10].Count.ToString();

            P3n1.Text = _forecasts[5].Count.ToString();
            P3n2.Text = _forecasts[8].Count.ToString();
            P3n3.Text = _forecasts[11].Count.ToString();
        }
        //############## LEFT SIDE #########################
        private void initHeadingLabelTitleObjects () {
            int topMargin = 55;
            int leftMargin = 30;

            Dictionary<String, String> headers = new Dictionary<string, string>();
            headers.Add("lbId", kad2SimSoft.Properties.Resources.lbId);
            headers.Add("lbPrice", kad2SimSoft.Properties.Resources.lbPrice);
            headers.Add("lbAmount", kad2SimSoft.Properties.Resources.lbAmount);
            headers.Add("lbAmountPercent", kad2SimSoft.Properties.Resources.lbAmountPercent);
            headers.Add("lbStockCost", kad2SimSoft.Properties.Resources.lbStockCost);
            headers.Add("lbLeadTime", kad2SimSoft.Properties.Resources.lbProcureLeadTime);
            foreach (var header in headers) {
                CustomLabel customLabel = new CustomLabel(header.Key, header.Value, new Thickness(leftMargin, topMargin, 0, 0), 60);
                customLabel.Width = 60;
                LayoutRoot.RegisterName(customLabel.Name, customLabel);
                LayoutRoot.Children.Add(customLabel);


                leftMargin += 67;
            }
        }
        private void initHeadingTextBoxObjects () {
            int topMargin = 120;
            int leftMargin = 30;

            double result;
            foreach (PurchasedPart part in _purchasedParts) {
                #region ID
                CustomTextBox txtBoxId = new CustomTextBox(
                    string.Format("txtBoxId_{0}", part.Id.ToString()),
                    string.Format("K {0}", part.Id.ToString()),
                    new Thickness(leftMargin, topMargin, 0, 0),
                    60,
                    string.Format("{0}", kad2SimSoft.Properties.Resources.tpIdPurchasedPart.ToString())
                    );
                txtBoxId.Style = txtBoxStyle.Style;
                txtBoxId.TextAlignment = TextAlignment.Left;
                dictTbPartIDs.Add(part.Id, txtBoxId);
                LayoutRoot.RegisterName(txtBoxId.Name, txtBoxId);
                LayoutRoot.Children.Add(txtBoxId);
                #endregion
                #region Price
                CustomTextBox txtBoxPrice = new CustomTextBox(
                    string.Format("txtBoxPrice_{0}", part.Id.ToString()),
                    string.Format("{0:0.00} €", part.Price),
                    new Thickness(leftMargin + 65, topMargin, 0, 0),
                    60,
                    string.Format("{0}", kad2SimSoft.Properties.Resources.tpPricePurchasedPart.ToString())
                    );
                txtBoxPrice.Style = txtBoxStyle.Style;
                LayoutRoot.RegisterName(txtBoxPrice.Name, txtBoxPrice);
                LayoutRoot.Children.Add(txtBoxPrice);
                #endregion
                #region Amount
                CustomTextBox txtBoxAmount = new CustomTextBox(string.Format("txtBoxAmount_{0}", part.Id.ToString()),
                    string.Format("{0:0,0}x", part.Amount),
                    new Thickness(leftMargin + (2 * 65), topMargin, 0, 0),
                    60,
                    string.Format("{0}", kad2SimSoft.Properties.Resources.tpAmountPurchasedPart.ToString())
                    );
                txtBoxAmount.setStyle = txtBoxStyle.Style;
                LayoutRoot.RegisterName(txtBoxAmount.Name, txtBoxAmount);
                LayoutRoot.Children.Add(txtBoxAmount);
                #endregion
                #region AmountPercent
                result = (System.Math.Round(
                    (double)100 /
                    double.Parse(part.StartAmount.ToString(), System.Globalization.CultureInfo.InvariantCulture) *
                    double.Parse(part.Amount.ToString(), System.Globalization.CultureInfo.InvariantCulture)
                    , 1));
                CustomTextBox txtBoxAmountPercent = new CustomTextBox(
                    string.Format("txtBoxAmountinPercent_{0}", part.Id.ToString()),
                    string.Format("{0:0.00}%", result),
                    new Thickness(leftMargin + (3 * 65), topMargin, 0, 0),
                    60,
                    string.Format("{0}", kad2SimSoft.Properties.Resources.tpAmountPercentPurchasedPart.ToString())
                    );

                txtBoxAmountPercent.setStyle = txtBoxStyle.Style;
                LayoutRoot.RegisterName(txtBoxAmountPercent.Name, txtBoxAmountPercent);
                LayoutRoot.Children.Add(txtBoxAmountPercent);
                #endregion
                #region StockCosts
                result = (System.Math.Round(
                    (double.Parse(part.Amount.ToString(), System.Globalization.CultureInfo.InvariantCulture) *
                    double.Parse(part.Price.ToString(), System.Globalization.CultureInfo.InvariantCulture)) / 100
                    , 1));
                CustomTextBox txtBoxStockCost = new CustomTextBox(
                    string.Format("txtBoxStockCost_{0}", part.Id.ToString()),
                    string.Format("{0:0.00} €", result.ToString()),
                    new Thickness(leftMargin + (4 * 65), topMargin, 0, 0),
                    60,
                    string.Format("{0}", kad2SimSoft.Properties.Resources.tpStockCostPurchasedPart.ToString())
                    );
                txtBoxStockCost.setStyle = txtBoxStyle.Style;
                LayoutRoot.RegisterName(txtBoxStockCost.Name, txtBoxStockCost);
                LayoutRoot.Children.Add(txtBoxStockCost);
                #endregion
                #region LeadTime
                CustomTextBox txtBoxProcureLeadTime = new CustomTextBox(
                    string.Format("txtBoxProcureLeadTime_{0}", part.Id.ToString()),
                    part.ProcureLeadTime.ToString(),
                    new Thickness(leftMargin + (5 * 65), topMargin, 0, 0),
                    60,
                    string.Format("{0} {1}{2} +/-{3}{4}", kad2SimSoft.Properties.Resources.tpLeadTimePurchasedPart.ToString(), "(", kad2SimSoft.Properties.Resources.lbOrderDeviation, part.OrderDeviation.ToString(), ")")
                    );
                txtBoxProcureLeadTime.setStyle = txtBoxStyle.Style;
                LayoutRoot.RegisterName(txtBoxProcureLeadTime.Name, txtBoxProcureLeadTime);
                LayoutRoot.Children.Add(txtBoxProcureLeadTime);
                #endregion

                if (isAlternateRow) {
                    txtBoxId.Background = Brushes.DimGray;
                    txtBoxPrice.Background = Brushes.DimGray;
                    txtBoxAmount.Background = Brushes.DimGray;
                    txtBoxAmountPercent.Background = Brushes.DimGray;
                    txtBoxStockCost.Background = Brushes.DimGray;
                    txtBoxProcureLeadTime.Background = Brushes.DimGray;


                    txtBoxStockCost.Foreground = Brushes.White;
                    txtBoxId.Foreground = Brushes.White;
                    txtBoxPrice.Foreground = Brushes.White;
                    txtBoxAmount.Foreground = Brushes.White;
                    txtBoxAmountPercent.Foreground = Brushes.White;
                    txtBoxProcureLeadTime.Foreground = Brushes.White;

                    isAlternateRow = false;
                }
                else {
                    isAlternateRow = true;
                }

                topMargin += 25;
            }
        }
        //############## MID ###############################
        private void initImgObjects () {
            int imgTopMargin = 121;
            #region calcPeriods
            foreach (PurchasedPart part in _purchasedParts) {
                ImageSource imgSourceP0 = null, imgSourceP1 = null, imgSourceP2 = null, imgSourceP3 = null;

                int stockAmount = part.Amount;
                int incomingAmount = part.FutureInWardAmount;
                int sumAmount = stockAmount + incomingAmount;

                bool fastOrdery = false;

                int result_P0, result_P1, result_P2, result_P3;
                result_P0 =
                    (part.UsedInP1 * Convert.ToInt16(P1n.Text)) +
                    (part.UsedInP2 * Convert.ToInt16(P2n.Text)) +
                    (part.UsedInP3 * Convert.ToInt16(P3n.Text));

                result_P1 =
                    (part.UsedInP1 * Convert.ToInt16(P1n1.Text)) +
                    (part.UsedInP2 * Convert.ToInt16(P2n1.Text)) +
                    (part.UsedInP3 * Convert.ToInt16(P3n1.Text));

                result_P2 =
                    (part.UsedInP1 * Convert.ToInt16(P1n2.Text)) +
                    (part.UsedInP2 * Convert.ToInt16(P2n2.Text)) +
                    (part.UsedInP3 * Convert.ToInt16(P3n2.Text));

                result_P3 =
                      (part.UsedInP1 * Convert.ToInt16(P1n3.Text)) +
                      (part.UsedInP2 * Convert.ToInt16(P2n3.Text)) +
                      (part.UsedInP3 * Convert.ToInt16(P3n3.Text));
                //sumamount <> stockamount
                #region P0
                if (sumAmount >= result_P0) {
                    if (sumAmount > (result_P0 + result_P1)) {
                        imgSourceP0 = imgGreen.Source;
                    }
                    else {
                        imgSourceP0 = imgOrange.Source;
                        if ((_actualPeriod + (part.ProcureLeadTime + part.OrderDeviation)) > (_actualPeriod + 1)) {
                            fastOrdery = true;
                        }
                    }
                }
                else if (sumAmount < result_P0) {
                    imgSourceP0 = imgRed.Source;
                    if ((_actualPeriod + part.ProcureLeadTime + part.OrderDeviation) > (_actualPeriod + 1)) {
                        fastOrdery = true;
                    }
                }
                #endregion
                #region P1
                sumAmount -= result_P0;
                if (sumAmount >= result_P1) {
                    if (sumAmount > (result_P1 + result_P2)) {
                        imgSourceP1 = imgGreen.Source;
                    }
                    else {
                        imgSourceP1 = imgOrange.Source;
                    }
                }
                else if (sumAmount < result_P1) {
                    imgSourceP1 = imgRed.Source;
                }
                #endregion
                #region P2
                sumAmount -= result_P1;
                if (sumAmount >= result_P2) {
                    if (sumAmount > (result_P2 + result_P3)) {
                        imgSourceP2 = imgGreen.Source;
                    }
                    else {
                        imgSourceP2 = imgOrange.Source;
                    }
                }
                else if (sumAmount < result_P2) {
                    imgSourceP2 = imgRed.Source;
                }
                #endregion
                #region P3
                sumAmount -= result_P2;
                if (sumAmount >= result_P3) {
                    if (sumAmount > (result_P3 + 0)) {
                        imgSourceP3 = imgGreen.Source;
                    }
                    else {
                        imgSourceP3 = imgOrange.Source;
                    }
                }
                else if (sumAmount < result_P3) {
                    imgSourceP3 = imgRed.Source;
                }
                #endregion

                #region AddImages
                CustomImgBox customImgP0 = new CustomImgBox(
                    String.Format("imgPeriod0_K{0}", part.Id.ToString()), imgSourceP0, new Thickness(441, imgTopMargin, 0, 0),
                    Convert.ToString(part.Amount - result_P0 + incomingAmount), part, result_P0);
                LayoutRoot.RegisterName(customImgP0.Name, customImgP0);
                LayoutRoot.Children.Add(customImgP0);

                CustomImgBox customImgP1 = new CustomImgBox(
                    String.Format("imgPeriod1_K{0}", part.Id.ToString()), imgSourceP1, new Thickness(478, imgTopMargin, 0, 0),
                    Convert.ToString(part.Amount - (result_P0 + result_P1) + incomingAmount), part, result_P1);
                LayoutRoot.RegisterName(customImgP1.Name, customImgP1);
                LayoutRoot.Children.Add(customImgP1);

                CustomImgBox customImgP2 = new CustomImgBox(
                    String.Format("imgPeriod2_K{0}", part.Id.ToString()), imgSourceP2, new Thickness(515, imgTopMargin, 0, 0),
                    Convert.ToString(part.Amount - (result_P0 + result_P1 + result_P2) + incomingAmount), part, result_P2);
                LayoutRoot.RegisterName(customImgP2.Name, customImgP2);
                LayoutRoot.Children.Add(customImgP2);

                CustomImgBox customImgP3 = new CustomImgBox(
                    String.Format("imgPeriod3_K{0}", part.Id.ToString()), imgSourceP3, new Thickness(549, imgTopMargin, 0, 0),
                    Convert.ToString(part.Amount - (result_P0 + result_P1 + result_P2 + result_P3) + incomingAmount), part, result_P3);
                LayoutRoot.RegisterName(customImgP3.Name, customImgP3);
                LayoutRoot.Children.Add(customImgP3);
                #endregion


                int recom = part.Amount - (result_P0 + result_P1 + result_P2 + result_P3) + incomingAmount;
                if (recom < 0) {
                    recom = recom * (-1);
                    if (recom > (part.DiscountQuantity * 0.8) && recom < part.DiscountQuantity) {
                        recom = part.DiscountQuantity;
                    }
                }
                else {
                    recom = 0;
                }

                initFollowingObjects(part, imgTopMargin, recom, fastOrdery);
                imgTopMargin += 25;
            }
            #endregion
        }
        //############## RIGHT SIDE ########################
        private void initFollowingLabelTitleObjects () {
            int topMargin = 50;
            int leftMargin = 580;

            Dictionary<String, String> headers = new Dictionary<string, string>();
            headers.Add("lbIncomingOrders", kad2SimSoft.Properties.Resources.lbOrderedParts.ToString());
            headers.Add("lbRecom", kad2SimSoft.Properties.Resources.lbRecommendedOrders.ToString());
            headers.Add("lbOrder", kad2SimSoft.Properties.Resources.lbOrderedPartsAmount.ToString());
            headers.Add("lbOrderType", kad2SimSoft.Properties.Resources.chbOrderType);
            headers.Add("lbOrderCost", kad2SimSoft.Properties.Resources.lbOrderCostTitle.ToString());
            headers.Add("lbOrderCostinSum", kad2SimSoft.Properties.Resources.lbOrderCostinSum.ToString());

            foreach (var header in headers) {
                CustomLabel customLabel = new CustomLabel(header.Key, header.Value, new Thickness(leftMargin, topMargin, 0, 0), 60);
                LayoutRoot.RegisterName(customLabel.Name, customLabel);
                LayoutRoot.Children.Add(customLabel);
                leftMargin += 66;
            }
        }
        private void initFollowingObjects (PurchasedPart part, int topMargin, int recom, bool fastOrdery) {
            int leftMargin = 580;
            #region IncomingOrders
            //if (part.FutureInWardAmount != 0) {
            CustomTextBox txtBoxFutureInward = new CustomTextBox(
                string.Format("txtBoxIncomingOrders_{0}", part.Id.ToString()),
                string.Format("{0}", part.FutureInWardAmount.ToString()),
                new Thickness(leftMargin, topMargin, 0, 0),
                60,
                string.Format("{0}", kad2SimSoft.Properties.Resources.tpIncomingParts)
                );
            txtBoxFutureInward.Style = txtBoxStyle.Style;
            txtBoxFutureInward.Background = dictTbPartIDs[part.Id].Background;

            LayoutRoot.RegisterName(txtBoxFutureInward.Name, txtBoxFutureInward);
            LayoutRoot.Children.Add(txtBoxFutureInward);
            //}
            #endregion
            #region RecommandationsLocked
            double ordercost = 0;

            //ordercost = part.OrderCosts + (recom * part.Price);
            //if (recom > part.DiscountQuantity) {
            //    ordercost = ordercost * 0.9;
            //}
            if (recom >= part.DiscountQuantity) {
                ordercost = part.OrderCosts + (recom * (part.Price * 0.9));
            }
            else {
                ordercost = part.OrderCosts + (recom * part.Price);
            }


            //if (recom != 0) {

            CustomTextBox txtBoxRecom = new CustomTextBox(
                string.Format("txtBoxRecommended_{0}", part.Id.ToString()),
                string.Format("{0}", recom),
                new Thickness(leftMargin + (1 * 65), topMargin, 0, 0),
                60,
                string.Format("{0} {1})", kad2SimSoft.Properties.Resources.tpRecomendedOrders, part.DiscountQuantity)
                );
            txtBoxRecom.Style = txtBoxStyle.Style;
            txtBoxRecom.Background = dictTbPartIDs[part.Id].Background;
            LayoutRoot.RegisterName(txtBoxRecom.Name, txtBoxRecom);
            LayoutRoot.Children.Add(txtBoxRecom);

            ordercost = part.OrderCosts + (recom * part.Price);
            //}
            #endregion
            #region Order
            CustomTextBox txtOrder = new CustomTextBox(
                string.Format("txtBoxOrder_{0}", part.Id.ToString()),
                string.Format("{0}", recom),
                new Thickness(leftMargin + (2 * 65), topMargin, 0, 0),
                60,
                string.Format("{0}", kad2SimSoft.Properties.Resources.tpOrder)
                );
            txtOrder.Style = txtBoxStyle.Style;
            txtOrder.TextChanged += txtBoxStyle2_TextChanged;
            txtOrder.Cursor = Cursors.Pen;
            txtOrder.IsReadOnly = false;
            txtOrder.Background = Brushes.RoyalBlue;

            LayoutRoot.RegisterName(txtOrder.Name, txtOrder);
            LayoutRoot.Children.Add(txtOrder);

            dictTbOrders.Add(part.Id, txtOrder);

            #endregion
            #region CheckboxOrderType

            CheckBox chbOrderType = new CheckBox();
            chbOrderType.Name = string.Format("chbOrderType_{0}", part.Id.ToString());
            chbOrderType.Margin = new Thickness(leftMargin + (3 * 65) + 20, topMargin + 2, 0, 0);

            chbOrderType.IsChecked = fastOrdery;


            chbOrderType.HorizontalAlignment = HorizontalAlignment.Left;
            chbOrderType.VerticalAlignment = VerticalAlignment.Top;
            chbOrderType.Checked += CheckBox_Checked;
            chbOrderType.Unchecked += chBox_Unchecked;
            LayoutRoot.RegisterName(chbOrderType.Name, chbOrderType);
            LayoutRoot.Children.Add(chbOrderType);

            dictChbOrderTypes.Add(part.Id, chbOrderType);

            #endregion
            #region OrderCosts
            if (Convert.ToDouble(txtOrder.Text) == 0) {
                ordercost = 0;
            }
            CustomTextBox txtBoxOrderCost = new CustomTextBox(
                string.Format("txtBoxOrderCost_{0}", part.Id.ToString()),

                string.Format("{0:0.00}", ordercost),
                new Thickness(leftMargin + (4 * 65), topMargin, 0, 0),
                60,
                string.Format("{0}", kad2SimSoft.Properties.Resources.lbOrderCost)
                );
            txtBoxOrderCost.Style = txtBoxStyle.Style;
            txtBoxOrderCost.TextAlignment = TextAlignment.Left;
            txtBoxOrderCost.Background = dictTbPartIDs[part.Id].Background;
            dictTbOderCosts.Add(part.Id, txtBoxOrderCost);

            LayoutRoot.RegisterName(txtBoxOrderCost.Name, txtBoxOrderCost);
            LayoutRoot.Children.Add(txtBoxOrderCost);
            #endregion
            #region OrderCostsInSum
            if (Convert.ToDouble(txtOrder.Text) == 0) {
                ordercost = 0;
            }


            #endregion
        }
        //############## CONTROLS ##########################
        private void btOpenPurchasedPartsOverview_Click (object sender, RoutedEventArgs e) {
            //    PurchasedPartsPopUpWindow wdOverviewPurchasedParts = new PurchasedPartsPopUpWindow(_purchasedParts);
            //    wdOverviewPurchasedParts.Show();
        }
        private void btCalc_Click (object sender, RoutedEventArgs e) {
            foreach (PurchasedPart part in _purchasedParts) {
                foreach (var entry in dictTbOrders) {
                    if (Convert.ToDouble(entry.Value.Text) > 0) {
                        if (part.Id == entry.Key) {
                            part.OrderAmount = Convert.ToInt32(entry.Value.Text.ToString());
                            if (dictChbOrderTypes[entry.Key].IsChecked == true) {
                                part.OrderModus = 4;
                                //double cost = (Convert.ToDouble(dictTbOderCosts[entry.Key].Text)- part.OrderCosts + 500);
                                //dictTbOderCosts[entry.Key].Text = cost.ToString();

                            }
                            else {
                                part.OrderModus = 5;

                            }
                        }
                    }
                }
            }
            double sum = 0;
            foreach (var entry in dictTbOderCosts) {
                sum += Convert.ToDouble(entry.Value.Text);
            }
            if (dictTbOrderCostInSum.Count > 0) {
                dictTbOrderCostInSum[0].Text = string.Format("{0:0.00}", sum);
            }
        }
        private void btBack_Click (object sender, RoutedEventArgs e) {
            FindPageControl(this).btPurchasingPlanning.IsChecked = false;
            FindPageControl(this).btCapacityPlanning.IsChecked = true;
            FindPageControl(this).ChangeViewTo(MainWindow.VIEWTYPE.CAPACITY);
        }
        private void btNext_Click (object sender, RoutedEventArgs e) {
            FindPageControl(this).RibbonButton_XMLExport_Click(null, null);
            FindPageControl(this).setButtonsEnable();
        }

        private void txtBoxStyle2_TextChanged (object sender, TextChangedEventArgs e) {

            TextBox currentTb = e.Source as TextBox;
            if (string.IsNullOrWhiteSpace(currentTb.Text) | Char.IsDigit(currentTb.Text, 0) == false) {
                currentTb.Text = "0";
            }
            TextBox focusedTb = e.Source as TextBox;
            double ordercost = 0;
            foreach (var entry in dictTbOrders) {
                if (entry.Key == Convert.ToInt32((focusedTb.Name.Substring(focusedTb.Name.Length - 2)))) {
                    foreach (PurchasedPart part in _purchasedParts) {
                        if (part.Id == entry.Key) {
                            double orderedAmount = Convert.ToDouble(dictTbOrders[entry.Key].Text);
                            if (orderedAmount > 0) {
                                if (orderedAmount >= part.DiscountQuantity) {
                                    if (dictChbOrderTypes[part.Id].IsChecked == true) {
                                        ordercost = (part.OrderCosts * 10) + (orderedAmount * (part.Price * 0.9));
                                    }
                                    else {
                                        ordercost = part.OrderCosts + (orderedAmount * (part.Price * 0.9));
                                    }
                                }
                                else {
                                    if (dictChbOrderTypes[part.Id].IsChecked == true) {
                                        ordercost = (part.OrderCosts * 10) + (orderedAmount * part.Price);
                                    }
                                    else {
                                        ordercost = part.OrderCosts + (orderedAmount * part.Price);
                                    }
                                    //ordercost = part.OrderCosts + (orderedAmount * part.Price);
                                }
                            }
                        }
                    }
                    dictTbOderCosts[entry.Key].Text = string.Format("{0:0.00}", ordercost.ToString());
                }
            }

            btCalc_Click(sender, e);
            double sum = 0;
            foreach (var entry in dictTbOderCosts) {
                sum += Convert.ToDouble(entry.Value.Text);
            }
            if (dictTbOrderCostInSum.Count > 0) {
                dictTbOrderCostInSum[0].Text = string.Format("{0:0.00}", sum);
            }
        }
        private void CheckBox_Checked (object sender, RoutedEventArgs e) {
            CheckBox pressedChb = e.Source as CheckBox;
            double ordercost = 0;
            foreach (var entry in dictChbOrderTypes) {
                if (entry.Key == Convert.ToInt32((pressedChb.Name.Substring(pressedChb.Name.Length - 2)))) {
                    foreach (PurchasedPart part in _purchasedParts) {
                        if (part.Id == entry.Key) {
                            double orderedAmount = Convert.ToDouble(dictTbOrders[entry.Key].Text);
                            if (orderedAmount > 0) {
                                if (orderedAmount >= part.DiscountQuantity) {
                                    ordercost = (part.OrderCosts * 10) + (orderedAmount * (part.Price * 0.9));
                                }
                                else {
                                    ordercost = (part.OrderCosts * 10) + (orderedAmount * part.Price);
                                }
                            }
                        }
                    }
                    //double cost = (Convert.ToDouble(dictTbOderCosts[entry.Key].Text) - partOrderCost + 500);
                    dictTbOderCosts[entry.Key].Text = string.Format("{0:0.00}", ordercost.ToString());
                }
                btCalc_Click(sender, e);
            }
        }
        private void chBox_Unchecked (object sender, RoutedEventArgs e) {
            CheckBox pressedChb = e.Source as CheckBox;
            double ordercost = 0;
            foreach (var entry in dictChbOrderTypes) {
                if (entry.Key == Convert.ToInt32((pressedChb.Name.Substring(pressedChb.Name.Length - 2)))) {
                    foreach (PurchasedPart part in _purchasedParts) {
                        if (part.Id == entry.Key) {
                            double orderedAmount = Convert.ToDouble(dictTbOrders[entry.Key].Text);
                            if (orderedAmount > 0) {
                                if (orderedAmount >= part.DiscountQuantity) {
                                    ordercost = part.OrderCosts + (orderedAmount * (part.Price * 0.9));
                                }
                                else {
                                    ordercost = part.OrderCosts + (orderedAmount * part.Price);
                                }
                            }
                        }
                    }
                    dictTbOderCosts[entry.Key].Text = string.Format("{0:0.00}", ordercost.ToString());
                }
                btCalc_Click(sender, e);
            }
        }
        private void UserControl_Loaded (object sender, RoutedEventArgs e) {
            _orders = FindPageControl(this).ProducionPlanningView.CreateListOforders();

            if (!isLoaded) {
                #region SumTextBox
                CustomTextBox txtBoxOrderCostinSum = new CustomTextBox(
                "txtBoxOrderCostinSum",
                "",
                new Thickness(580 + (5 * 65), 121, 0, 0),
                60,
                string.Format("{0}", kad2SimSoft.Properties.Resources.tpOrderCostinSum)
                );

                txtBoxOrderCostinSum.Style = txtBoxStyle.Style;
                txtBoxOrderCostinSum.TextAlignment = TextAlignment.Right;
                txtBoxOrderCostinSum.Background = Brushes.Gold;
                txtBoxOrderCostinSum.Foreground = Brushes.Black;
                dictTbOrderCostInSum.Add(0, txtBoxOrderCostinSum);

                LayoutRoot.RegisterName(txtBoxOrderCostinSum.Name, txtBoxOrderCostinSum);
                LayoutRoot.Children.Add(txtBoxOrderCostinSum);
                #endregion

                Pn.Content = _actualPeriod.ToString();
                Pn1.Content = _actualPeriod + 1;
                Pn2.Content = _actualPeriod + 2;
                Pn3.Content = _actualPeriod + 3;

                initTextBoxesForecasts();

                initHeadingLabelTitleObjects();
                initHeadingTextBoxObjects();

                initFollowingLabelTitleObjects();

                initImgObjects();



                btCalc_Click(sender, e);
                FindPageControl(this).btExportXML.IsEnabled = true;

                isLoaded = true;
            }
        }
        //############## INTERNAL CUSTOM CONTROLS ########
        internal class CustomLabel : Label {
            public CustomLabel (string customLableName, string text, Thickness margin, int width) {
                TextBlock tb = new TextBlock();
                tb.IsHyphenationEnabled = true;
                tb.Text = text;
                tb.FontWeight = FontWeights.Bold;
                tb.TextWrapping = TextWrapping.Wrap;
                tb.TextAlignment = TextAlignment.Center;
                this.FontWeight = FontWeights.Bold;
                Name = customLableName;
                HorizontalAlignment = HorizontalAlignment.Left;
                VerticalAlignment = VerticalAlignment.Top;
                Content = string.Format("{0}", text);


                Margin = margin;
                Width = width;
                Content = tb;
            }
        }
        internal class CustomTextBox : TextBox {
            string _tp;
            public CustomTextBox (string customTextBoxName, string text, Thickness margin, int width, string tooltip) {
                TextAlignment = TextAlignment.Right;
                HorizontalAlignment = HorizontalAlignment.Left;
                VerticalAlignment = VerticalAlignment.Top;
                Name = customTextBoxName;
                Text = string.Format("{0}", text);
                Width = width;
                Margin = margin;
                this.IsReadOnly = true;
                Cursor = Cursors.Arrow;
                ToolTip _tooltip = new ToolTip { Content = tooltip };
                this.ToolTip = tooltip;
                this._tp = tooltip;
            }

            //public void filterColours (double min, double max, double value) {
            //    if (value < min | value > max) {
            //        //BorderBrush = Brushes.Red;
            //        //                    Background = Brushes.LightSalmon;
            //        //                  Foreground = Brushes.Black;
            //    }
            //    else {
            //        //BorderBrush = Brushes.Green;
            //        //                Background = Brushes.Aqua;
            //        //              Foreground = Brushes.Black;
            //    }
            //    string tooltip = string.Format("{2}, Values under '{0}' and above '{1}' are marked", min, max, _tp);
            //    ToolTip _tooltip = new ToolTip { Content = tooltip };
            //    this.ToolTip = tooltip;
            //}

            public Style setStyle {
                get { return this.Style; }
                set { this.Style = value; }
            }

        }
        internal class CustomImgBox : Image {
            public CustomImgBox (string name, ImageSource source, Thickness margin, string sum, PurchasedPart part, int result) {
                this.HorizontalAlignment = HorizontalAlignment.Left;
                this.VerticalAlignment = VerticalAlignment.Top;
                Name = name;
                Height = 16;
                Width = 20;
                Margin = margin;
                Source = source;
                string tp = string.Format(
                    "{0} '{1}' {2} '{5}' \n{0} '{1}' {3} '{6}' \n{0} '{1}' {4} '{7}' \n{0} '{1}' {8} '{9}' \n{10} '{11}'",
                    kad2SimSoft.Properties.Resources.tpImagesPart,
                    part.Id.ToString(),
                    kad2SimSoft.Properties.Resources.tpImagesUsedinOne,
                    kad2SimSoft.Properties.Resources.tpImagesUsedinTwo,
                    kad2SimSoft.Properties.Resources.tpImagesUsedinThree,
                    part.UsedInP1,
                    part.UsedInP2,
                    part.UsedInP3,
                    kad2SimSoft.Properties.Resources.tpImagesUsedinSum,
                    result,
                    kad2SimSoft.Properties.Resources.tpImagesAmountAfter,
                    sum
                    );

                ToolTip _tooltip = new ToolTip { Content = tp };


                this.ToolTip = _tooltip;
            }
        }
    }
}
